<script lang="ts" setup>
import {
  FileTextOutlined,
  LinkOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { h, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { CourseFile, SourceFile } from '@/types/course/course';
import { getFolderInfoApi, getSourceFileUrlApi } from '@/api/study/course';

// Reactive state
const scheduleData = ref<CourseFile[]>([]);

// Router and Route
const router = useRouter();
const route = useRoute();

// Fetch course files
const fetchCourseFiles = async () => {
  const { folderId, courseId } = route.params as { folderId: string; courseId: string };

  if (!folderId || !courseId) {
    console.error('缺少必要的参数: folderId, courseId 或 accessToken');
    return;
  }

  localStorage.setItem('courseId', courseId);
  localStorage.setItem('folderId', folderId);

  try {
    const response = await getFolderInfoApi(folderId);

    const childFiles: CourseFile[] = response?.childFiles;

    if (Array.isArray(childFiles)) {
      scheduleData.value = childFiles;
    }
    else {
      console.error('childFiles 不是数组或未定义:', childFiles);
      scheduleData.value = [];
    }
  }
  catch (error) {
    console.error('获取课程文件时出错:', error);
  }
};

const handleDocumentClick = async (file: SourceFile | CourseFile) => {
  const sourceId = 'sourceId' in file ? file.sourceId : file.courseFileId;
  const sourcePath = 'sourcePath' in file ? file.sourcePath : undefined;
  const { courseId, folderId } = route.params as { courseId: string; folderId: string };

  if (!sourceId || !courseId || !folderId)
    return;

  router.push({ name: 'LearningDetails', params: { courseId, folderId, sourceId, filePath: sourcePath } });
};

const handleVideoClick = async (file: SourceFile | CourseFile) => {
  const sourceId = 'sourceId' in file ? file.sourceId : file.courseFileId;
  const sourcePath = 'sourcePath' in file ? file.sourcePath : undefined;
  const { courseId, folderId } = route.params as { courseId: string; folderId: string };

  if (!sourceId || !courseId || !folderId)
    return;

  router.push({ name: 'LearningDetails', params: { courseId, folderId, sourceId, filePath: sourcePath } });
};

const handleGenericResourceClick = async (file: SourceFile | CourseFile) => {
  const sourcePath = 'sourcePath' in file ? file.sourcePath : ('filePath' in file ? file.filePath : undefined);
  if (sourcePath) {
    const resourceUrl = `/path/to/resource/${sourcePath}`; // 根据实际情况修改
    window.open(resourceUrl, '_blank');
  }
  else {
    console.error('资源路径为空');
    message.error('资源路径为空');
  }
};

const handleWebClick = async (file: SourceFile | CourseFile) => {
  const sourceId = 'sourceId' in file ? file.sourceId : file.courseFileId;

  if (!sourceId) {
    console.error('未提供 sourceId');
    message.error('未提供 sourceId');
    return;
  }

  try {
    const response = await getSourceFileUrlApi(sourceId);

    const fileUrl = response;
    if (fileUrl) {
      window.open(fileUrl, '_blank');
    }
    else {
      console.error('获取文件URL失败');
      message.error('获取文件URL失败');
    }
  }
  catch (error) {
    console.error('请求失败:', error);
    message.error('请求失败');
  }
};

// Resource click handlers
const handleResourceClick = async (file: SourceFile | CourseFile) => {
  // console.log('点击了资源:', file);

  switch (file.tag) {
    case '文档':
      await handleDocumentClick(file);
      break;
    case '音视频':
      await handleVideoClick(file);
      break;
    case '资源':
      await handleGenericResourceClick(file);
      break;
    case '网页资源':
      await handleWebClick(file);
      break;
    default:
      console.error('未知的资源类型:', file.tag);
      message.error('未知的资源类型');
      break;
  }
};

// Helper to get icons based on tag
const getIcon = (tag: string) => {
  switch (tag) {
    case '文档':
      return h(FileTextOutlined);
    case '音视频':
      return h(VideoCameraOutlined);
    case '资源':
      return h(FileTextOutlined);
    case '网页资源':
      return h(LinkOutlined);
    default:
      return null;
  }
};

// Convert scheduleData to treeData for a-tree component
const treeData = ref<any[]>([]);

const generateTreeData = () => {
  treeData.value = scheduleData.value.map(chapter => ({
    title: chapter.name || '无名称',
    key: chapter.courseFileId,
    icon: getIcon(chapter.tag ? chapter.tag : ''),
    children: chapter.childFiles.map(section => ({
      title: section.name || '无名称',
      key: section.courseFileId,
      icon: getIcon(section.tag ? section.tag : ''),
      children: section.sourceFiles.map(resource => ({
        title: resource.name || '无名称',
        key: resource.courseFileId || resource.sourceId,
        icon: getIcon(resource.tag),
        isLeaf: true,
        file: resource, // Attach the entire resource object for click handling
      })),
    })),
  }));
};

onMounted(fetchCourseFiles);
watch(scheduleData, generateTreeData, { immediate: true });

// Handle tree item click
const onTreeClick = (selectedKeys: string[], info: any) => {
  const node = info.node;

  if (node.isLeaf && node.file)
    handleResourceClick(node.file);
};
</script>

<template>
  <div class="tabTitle">
    课程目录
  </div>
  <div class="tabs">
    <a-tree
      :tree-data="treeData"
      show-icon
      :selectable="true"
      :block-node="true"
      class="course-tree"
      @select="onTreeClick"
    />
  </div>
</template>

<style scoped lang="scss">
.tabTitle {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}
.tabs {

  .course-tree {
    width: 100%;
  }

  .ant-tree-node-content-wrapper {
    padding-left: 8px !important;
    padding-right: 8px !important;
  }

  .ant-tree-switcher {
    margin-right: 4px !important;
  }

  .ant-tree-node {
    margin-bottom: 4px;
  }

  .ant-tree-treenode .ant-tree-node-selected {
    background-color: transparent !important;
  }

  .resourceItem {
    display: flex;
    align-items: center;

    .ant-tree-title {
      display: flex;
      align-items: center;
      font-size: 1rem;
    }

    &:hover .ant-tree-title {
      background-color: #f5f5f5;
    }

    .anticon {
      font-size: 1rem;
      margin-right: 8px;
      color: rgba(0, 0, 0, 0.65);
    }
  }

  /* Responsive adjustments */
  @media (max-width: 768px) {
    .tabTitle {
      font-size: 1rem;
    }

    .ant-tree-title {
      font-size: 0.9rem;
    }

    .anticon {
      font-size: 0.9rem;
      margin-right: 6px;
    }
  }
}
</style>
